<?php


namespace App\Http\Repositories\Api\Qiniu;

use App\Exceptions\ApiException;
use App\Http\Repositories\BaseRepository as Repository;
use zgldh\QiniuStorage\QiniuStorage;

class QiniuRepository extends Repository
{
    const IMAGES_PREFIX = 'images/';

    /**
     *
     * @param $data
     * @return array
     * @throws ApiException
     */
    public function uploadFile($data)
    {
        $file = $data['file'];
        $res = [
            'src' => '',
            'path' => ''
            ];
        // 初始化
        $disk = QiniuStorage::disk('qiniu');
        // 重命名文件
        $fileName = $this->getFileNameMd5($file);
        // 上传到七牛
        $bool = $disk->put(self::IMAGES_PREFIX.$fileName, file_get_contents($file->getRealPath()));
        // 判断是否上传成功
        if ($bool) {
            $path = $disk->downloadUrl(self::IMAGES_PREFIX.$fileName);
            $res['path'] = $path;
            $res['src'] = $fileName;
            return $res;
        }
        throw new ApiException([1212, '上传失败']);

    }

    /**
     * 获取文件名
     * @param $file
     * @return string
     */
    public function getFileNameMd5($file)
    {
        return md5($file->getClientOriginalName()).'.'.$file->getClientOriginalExtension();
    }



}
